﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;

namespace LayoutEdit
{
    class LayoutFile
    {
        private string _filename;       // Name of the file
        private int _fileversion;       // Version of the file
        private Int64 _houseid;         // Unique House ID
        private Int64 _houseversion;    // Internal Identifier for House
        private string _housetype;      // House Type
        private bool _fileloaded;       // Do we have a file loaded?
        public DataTable HouseItems = new DataTable("HouseItems");
        private DateTime _lastModified;
        

        public string FileName
        {
            get { return _filename; }
            set
            {
                _filename = value;
                _fileloaded = LoadFile();
                if (!_fileloaded)
                {
                    _filename = string.Empty;
                    throw new FileNotFoundException("The file '" + value + "' either does not exist or is not a valid (Version 6) layout file");
                }
            }
        }
        public bool FileLoaded { get { return _fileloaded; } }
        public int FileVersion { get { return (_fileloaded) ? _fileversion : 0; } }
        public Int64 HouseID { get { return (_fileloaded) ? _houseid : 0; } }
        public string HouseType { get { return _housetype; } }
        public DateTime LastModified { get { return _lastModified; } set { _lastModified = value; } }
        public LayoutFile()
        {
            HouseItems.Columns.Add(new DataColumn("ItemName", typeof(string)));
            HouseItems.Columns.Add(new DataColumn("x", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("y", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("z", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("Rotation", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("Pitch", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("Roll", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("Scale", typeof(decimal)));
            HouseItems.Columns.Add(new DataColumn("InCrate", typeof(bool)));
            HouseItems.Columns.Add(new DataColumn("ItemID", typeof(Int64)));
            HouseItems.Columns.Add(new DataColumn("DatabaseID", typeof(Int32)));
            HouseItems.Columns.Add(new DataColumn("ID", typeof(int)));
            HouseItems.Columns["ID"].AutoIncrement = true;
        }
        private bool LoadFile()
        {
            if (!File.Exists(_filename)) return false;
            StreamReader sr = new StreamReader(_filename);
            string _input;

            _input = sr.ReadLine();
            if (_input.Split(',').Count() != 2) return false;
            _fileversion = int.Parse(_input.Split(',')[0]);
            if (_fileversion != 6) return false;

            _input = sr.ReadLine();
            _housetype = _input.Split(',')[1];
            _houseversion = Int64.Parse(_input.Split(',')[0]);

            _input = sr.ReadLine();
            _houseid = Int64.Parse(_input.Split(',')[0]);

            string[] _inpItem = new string[11];
            HouseItems.Clear();
            while (!sr.EndOfStream)
            {
                _input = sr.ReadLine();
                _inpItem = _input.Split(',');
                DataRow dr = HouseItems.NewRow();
                dr["ItemID"] = Int64.Parse(_inpItem[0]);
                dr["DatabaseID"] = Int32.Parse(_inpItem[1]);
                dr["x"] = decimal.Parse(_inpItem[2]);
                dr["z"] = decimal.Parse(_inpItem[3]);
                dr["y"] = decimal.Parse(_inpItem[4]);
                dr["Rotation"] = decimal.Parse(_inpItem[5]);
                dr["Pitch"] = decimal.Parse(_inpItem[6]);
                dr["Roll"] = decimal.Parse(_inpItem[7]);
                dr["Scale"] = decimal.Parse(_inpItem[8]);
                dr["InCrate"] = bool.Parse(_inpItem[9]);
                string ItemName = _inpItem[10];
                if (ItemName.Substring(ItemName.Length - 1, 1) == "\"")
                {
                    ItemName = _inpItem[10].Substring(1, _inpItem[10].Length - 2);
                }
                else
                {
                    ItemName = _inpItem[10];
                    ItemName += "," + _inpItem[11];
                    if (_inpItem.Count() > 12) ItemName += "," + _inpItem[12];
                    if (_inpItem.Count() > 13) ItemName += "," + _inpItem[13];
                    if (_inpItem.Count() > 14) ItemName += "," + _inpItem[14];
                    ItemName = ItemName.Substring(1, ItemName.Length - 2);
                }
                dr["ItemName"] = ItemName;
                HouseItems.Rows.Add(dr);
            }
            sr.Close();
            _lastModified = File.GetLastWriteTime(_filename);
            return true;
        }

        public bool SaveFile()
        {
            if (!_fileloaded) return false;
            return SaveFile(_filename);
        }
        public bool SaveFile(string FileName)
        {
            File.WriteAllText(FileName, "");
            StreamWriter sw = new StreamWriter(FileName);
            sw.WriteLine(_fileversion.ToString() + ",Version Number");
            sw.WriteLine(_houseversion.ToString() + "," + _housetype);
            sw.WriteLine(_houseid.ToString() + ", Unique House ID. ");
            string line;
            foreach (DataRow dr in HouseItems.Rows)
            {
                line = dr["ItemID"].ToString();
                line += ",";
                line += dr["DatabaseID"].ToString();
                line += ",";
                line += String.Format("{0:0.00000000}", dr["x"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["z"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["y"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["Rotation"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["Pitch"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["Roll"]);
                line += ",";
                line += String.Format("{0:0.00000000}", dr["Scale"]);
                line += ", ";
                line += dr["InCrate"].ToString().ToLower();
                line += ",";
                line += "\"" + dr["ItemName"] + "\"";
                sw.WriteLine(line);
            }
            sw.Close();
            if (FileName != _filename) { _filename = FileName; }
            System.Threading.Thread.Sleep(250);
            _lastModified = File.GetLastWriteTime(_filename);
            return true;

        }
        public void Refresh()
        {
            LoadFile();
            _lastModified = File.GetLastWriteTime(_filename);
        }
        internal void ItemstoDB(Placement.HouseItem[] Items)
        {
            foreach (Placement.HouseItem Item in Items)
            {
                foreach (DataRow dr in HouseItems.Rows)
                {
                    if ((int)dr["ID"] == Item.ID)
                    {
                        dr["ItemID"] = Item.ItemID;
                        dr["DatabaseID"] = Item.DatabaseID;
                        dr["x"] = Item.x;
                        dr["z"] = Item.z;
                        dr["y"] = Item.y;
                        dr["Rotation"] = Item.Rotation;
                        dr["Pitch"] = Item.Pitch;
                        dr["Roll"] = Item.Roll;
                        dr["Scale"] = Item.Scale;
                        dr["InCrate"] = Item.InCrate;
                        dr["ItemName"] = Item.ItemName;
                        break;
                    }
                }
            }
        }
    }
}
